import 'dart:convert';

import 'package:android_intent_plus/android_intent.dart';
import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:url_launcher/url_launcher.dart';

import '../AppConfig/Config.dart';
import '../AppConfig/LocalStorage.dart';
import '../AppConfig/RouteAct.dart';
import '../AppConfig/ShowDialog.dart';
import '../AppConfig/StringEncapsulation.dart';
import '../Message/SingleChatPage.dart';
import '../http/NoLoadingGetApi.dart';
import '../http/NoLoadingPostApi.dart';
import '../http/api.dart';
import '../l10n/messages.dart';
import 'package:platform/platform.dart';
class DriverIntroduction extends StatefulWidget {
  const DriverIntroduction({super.key, required this.DrvId});
  final String DrvId;
  @override
  State<DriverIntroduction> createState() => _DriverIntroductionState();
}

class _DriverIntroductionState extends State<DriverIntroduction> {
  Map driverUserMap={};
  List withMeDataList=[];
  List orderDataList=[];
  int checkType =0;
  List allTapList=[];
  List goodTapList=[];
  List midTapList=[];
  List badTapList=[];
  List showList=[];
  int current=1;
  List tagsList=["运费结算准时","运费结算准时","运费结算准时","运费结算准时","运费结算准时","运费结算准时","运费结算准时"];
  @override
  List<String> tagList = [
    '全部',
    '好评',
    '中评',
    '差评',
  ];
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getDrvUserDetailAction(widget.DrvId);
    allEvaluationAction(1);

    // postAdd();
  }
  void postAdd()async{
    String? sprId=await UserIdManager.getUserID();
    NoLoadingApiManager.postData(
      context,
      "api/auth/shipper/evaluation/add",
      {
        "waybillId":"12305",
        'driverId':widget.DrvId,
        "route":"苏州 吴中区/苏州 吴中区->苏州 吴中区/苏州 吴中区",
        "shipperId":sprId,
        "level":"POSITIVE",
        "tags":['认证负责',"运费结算准时","尊重司机","装卸货快"],
      },
          (responseData)  {
        setState(() {
        });
      },
    );
  }
  void allEvaluationAction(int current)async{
    String? sprId=await UserIdManager.getUserID();
    NoLoadinggetApiManager.getData(
      context,
      "api/auth/driver/evaluation/page",
      {'current':current,"size":20,"shipperId":sprId,"driverId":widget.DrvId,"level":""},
          (responseData)  {
        setState(() {
          if(responseData['data']['records'].isNotEmpty){
            allTapList=responseData['data']['records'];
            showList=allTapList;
          }

        });
      },
    );
  }
  void goodEvaluationAction(int current)async{
    String? sprId=await UserIdManager.getUserID();
    NoLoadinggetApiManager.getData(
      context,
      "api/auth/driver/evaluation/page",
      {'current':current,"size":20,"shipperId":sprId,"driverId":widget.DrvId,"level":"POSITIVE"},
          (responseData)  {
        setState(() {
          if(responseData['data']['records'].isNotEmpty){

            goodTapList=responseData['data']['records'];

          }

        });
      },
    );
  }
  void midEvaluationAction(int current)async{
    String? sprId=await UserIdManager.getUserID();
    NoLoadinggetApiManager.getData(
      context,
      "api/auth/driver/evaluation/page",
      {'current':current,"size":20,"shipperId":sprId,"driverId":widget.DrvId,"level":"NEUTRAL"},
          (responseData)  {
        setState(() {
          if(responseData['data']['records'].isNotEmpty){

            midTapList=responseData['data']['records'];

          }

        });
      },
    );
  }
  void badEvaluationAction(int current)async{
    String? sprId=await UserIdManager.getUserID();
    NoLoadinggetApiManager.getData(
      context,
      "api/auth/driver/evaluation/page",
      {'current':current,"size":20,"shipperId":sprId,"driverId":widget.DrvId,"level":"NEGATIVE"},
          (responseData)  {
        setState(() {
          if(responseData['data']['records'].isNotEmpty){
            badTapList=responseData['data']['records'];
          }else{
            current=current-1;
          }
        });
      },
    );
  }
  Future<void> getDrvUserDetailAction(String driverId) async {

    NoLoadinggetApiManager.getData(
      context,
      "api/auth/driver/user/getBriefUser",
      {'id':driverId},
          (responseData)  {
        setState(() {
          driverUserMap=responseData['data'];
        });
      },
    );
  }


  //移除熟车
  void deleMyDriverAction(String drvId)async{

    String? token = await TokenManager.getToken();
    dio.interceptors.add(InterceptorsWrapper(
        onRequest: (options, handler) async {
          options.headers["satoken"] = token;
          return handler.next(options);
        }
    ));
    dio
        .post(
      MyServiceUrl.header+'api/auth/shipper/driver/delete',
      data: [
        {"id": drvId,}
    ]
      ,
      options: Options(
        sendTimeout: Duration(seconds: 2),
        receiveTimeout: Duration(seconds: 5),
      ),

    )
        .then((r) {
      setState(() {
        print(r);
        Map<String, dynamic> jsonMap = json.decode(
            r.toString());
        // 获取code和data
        String code = jsonMap['code'].toString();
        if (code == "200") {
          print("code：$code");
          BrnToast.show("移除成功", context, duration: BrnDuration.short,);
          getDrvUserDetailAction(widget.DrvId);

        }
      });
    }).catchError((error) {
      print(error);
      ;
    });
  }

  //添加熟车
  void addMyDrivertAction()async{
    NoLoadingApiManager.postData(
      context,
      "api/auth/shipper/driver/add",
      {
        "driverId": widget.DrvId,
        "vehicleId": driverUserMap['vehicleId'],
      },
          (responseData)  {
        // setState(() {
          // driverUserMap=responseData['data'];
        // });
            getDrvUserDetailAction(widget.DrvId);
      },
    );
  }

  _makePhoneCall(String phoneNumber) async {
  if (LocalPlatform().isAndroid) {
    var status = await Permission.phone.status;
    if (status.isGranted) {
      // 权限已被授予
      // callPhone();
      final AndroidIntent intent = AndroidIntent(
        action: 'android.intent.action.CALL',
        data: Uri.encodeFull('tel:$phoneNumber'),
      );
      await intent.launch();
    } else if (status.isDenied) {
      // 权限被拒绝，但用户可以再次授权
      showCallPhoneFirstDialog(context);
      status = await Permission.phone.request();
      if (status.isGranted) {
        // 用户同意了权限
        // callPhone();
        final AndroidIntent intent = AndroidIntent(
          action: 'android.intent.action.CALL',
          data: Uri.encodeFull('tel:$phoneNumber'),
        );
        await intent.launch();
      } else {
        showCallPhoneDialog(context);
        // 用户拒绝权限，无法发起电话
        // 可以在此处展示信息提示用户需要权限
      }
    } else if (status.isPermanentlyDenied) {
      // 权限被永久拒绝，需要用户手动开启权限
      showCallPhoneDialog(context);
    }

    }else{
    final url =Uri.parse('tel:$phoneNumber');
    if (await canLaunchUrl(url)) {
      await launchUrl(url);
    } else {
      throw '无法拨打电话：$url';
    }
    }

  }
  Future _onRefresh() async {
    current=1;
    if(checkType==0)
      allEvaluationAction(1);
    if(checkType==1)
      goodEvaluationAction(1);
    if(checkType==2)
      midEvaluationAction(1);
    if(checkType==3)
      badEvaluationAction(1);

  }
  Future<void> _loadMoreData() async {
    // 加载更多数据后更新列表
    if (showList.length > 20 * current-1) {
      current = current + 1;
      if (checkType == 0)
        allEvaluationAction(current);
      if (checkType == 1)
        goodEvaluationAction(current);
      if (checkType == 2)
        if (showList.length > 20*current-1) {
          midEvaluationAction(current);
        }
      if (checkType == 3)
        badEvaluationAction(current);
    }
  }
  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    var messages = AppLocalizations.of(context)!;
    return Scaffold(
      backgroundColor: MyColors.backgreyColor,
      appBar: AppBar(
        centerTitle: true,
        backgroundColor: Colors.white,
        title: Text("司机简介",style: TextStyle(color: Colors.black,fontSize: 16.sp,fontWeight: FontWeight.w300),),
        actions: [
            TextButton(onPressed: (){
              addMyDrivertAction();
            }, child: Text("添加熟车",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp),)),
        ],
      ),
      body:driverUserMap.isEmpty?SizedBox(height: 0,):
      Column(
        children: [
          Expanded(child: ListView(
            children: [
              Container(
                padding: EdgeInsets.only(top: 10.h,bottom: 15.h,left: 15.w,right: 15.w),
                decoration: BoxDecoration(
                    gradient: LinearGradient(
                      colors: [Color.fromRGBO(246,239,232,1) ,Color.fromRGBO(247,238,234,1) ,Color.fromRGBO(243,238,235,1) ,Color.fromRGBO(239,237,235,1) ,Color.fromRGBO(239,237,235,1) ], // 渐变颜色数组
                      begin: Alignment.topLeft, // 渐变开始的位置
                      end: Alignment.bottomRight, // 渐变结束的位置
                    ),
                    borderRadius: BorderRadius.all(Radius.circular(10))),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      // crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Container(
                          width: 60.w,
                          height: 60.h,
                          child:  driverUserMap['avatarPath']!=null&&driverUserMap['avatarPath']!=""?
                          CircleAvatar(
                            radius: 15,
                            backgroundImage: NetworkImage(MyServiceUrl.imgHeader +driverUserMap['avatarPath']),
                          )
                              :
                          CircleAvatar(
                            radius: 15,
                            backgroundImage: AssetImage("lib/Images/login/默认头像.jpeg"),
                          ),
                        ),
                        SizedBox(width: 20.w,),
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(driverUserMap['realName'],style: TextStyle(color: Colors.black,fontSize: 18.sp,fontWeight: FontWeight.w600),),
                            Text(maskPhoneNumber(driverUserMap['phoneNum']),style: TextStyle(color: Colors.black,fontSize: 14.sp,),),
                          ],
                        ),


                      ],
                    ),
                    SizedBox(height: 15.h,),
                    Container(
                      // height: 10.h,
                      padding: EdgeInsets.only(top: 10.h),
                      decoration: BoxDecoration(
                          color: MyColors.backgreyColor,
                          borderRadius: BorderRadius.all(Radius.circular(10))),
                      child:Column(
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              SizedBox(),
                              Column(
                                children: [
                                  Text(driverUserMap['registerDuration']!=null?driverUserMap['registerDuration']+"天":"--",style: TextStyle(color: Colors.black,fontSize: 16.sp),),
                                  Text("注册时长",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp),),
                                ],
                              ),
                              Column(
                                children: [
                                  Text(driverUserMap['totalNum'].toString(),style: TextStyle(color: Colors.black,fontSize: 16.sp),),
                                  Text("累计交易量",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp),),
                                ],
                              ),
                              Column(
                                children: [
                                  Text(driverUserMap['rating'].toString()+"%",style: TextStyle(color: Colors.black,fontSize: 16.sp),),
                                  Text("好评率",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp),),
                                ],
                              ),
                              SizedBox(),
                            ],
                          ),
                          SizedBox(height: 10.h,),
                          Container(
                            padding: EdgeInsets.only(left: 15.w,top: 15.h,bottom: 10.h),
                            height: 50.h,
                            decoration: BoxDecoration(
                                gradient: LinearGradient(
                                  colors: [Color.fromRGBO(254,248,241, 1),Colors.white, Colors.white, Colors.white, Colors.white], // 渐变颜色数组
                                  begin: Alignment.topCenter, // 渐变开始的位置
                                  end: Alignment.bottomCenter, // 渐变结束的位置
                                ),
                                borderRadius: BorderRadius.all(Radius.circular(10))),
                            child: Row(

                              children: [
                                Text("信用星级",style: TextStyle(color: Colors.black,fontSize: 14.sp,fontWeight: FontWeight.w600),),

                                Row(
                                  children: List.generate( (divideAndRound(driverUserMap['rating'].toString(), 20)), (starIndex) {
                                    return Icon(Icons.star, color: MyColors.themeColor, size: 20.0);
                                  }),
                                ),
                                Row(
                                  children: List.generate( (divideAndRound((100-driverUserMap['rating']).toString(), 20)), (starIndex) {
                                    return Icon(Icons.star_outline, color: MyColors.themeColor, size: 20.0);
                                  }),
                                ),
                              ],),
                          ),
                        ],
                      ),
                    ),
                  ],),
              ),
              Container(
                decoration: BoxDecoration(
                    color: Colors.white,
                  ),
                margin: EdgeInsets.only(top: 8.h),
                padding:EdgeInsets.only(left: 17.w,top: 14.h,bottom: 10.h,right: 20.w) ,
                child: Column(
                  children: [
                    Row(
                      children: [
                        Image.asset("lib/Images/OrderList/司机简介车辆信息icon.png",width: 18.w,height: 18.h,),
                        SizedBox(width: 8.w,),
                        Text("车辆信息",style: TextStyle(color: Colors.black,fontSize: 14.sp),),

                      ],
                    ),
                    SizedBox(height: 5.h,),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Text(driverUserMap['vehicleNum'],style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Text("车长",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp,)),
                            SizedBox(height: 10.h,),
                            Text(driverUserMap['vehicleLength'].toString(),style: TextStyle(color: Colors.black,fontSize: 13.sp),),
                          ],
                        ),
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Text("车型",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp,)),
                            SizedBox(height: 10.h,),
                            Text(driverUserMap['vehicleModel'].toString(),style: TextStyle(color: Colors.black,fontSize: 13.sp),),
                          ],
                        ),
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Text("载重",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp,)),
                            SizedBox(height: 10.h,),
                            Text((driverUserMap['vehicleTonnage']).toString()+"吨",style: TextStyle(color: Colors.black,fontSize: 13.sp),),
                          ],
                        ),
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Text("车龄",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp,)),
                            SizedBox(height: 10.h,),

                            Text(driverUserMap['vehicleAge']!=null?driverUserMap['vehicleAge'].toString()+"年":"--",style: TextStyle(color: Colors.black,fontSize: 13.sp),),
                          ],
                        ),
                      ],
                    )
                  ],
                ),
              ),
              SizedBox(height: 8.h,),
              Container(
                color: Colors.white,
                padding: EdgeInsets.only(left: 15.w,top: 10.h,bottom: 10.h),
                child:    Text("评价",style: TextStyle(color: Colors.black,fontSize: 16.sp,fontWeight: FontWeight.w600),),
              ),
              Container(
                  margin: EdgeInsets.only(top: 1.h),
                  padding: EdgeInsets.only(left: 15.w,top: 10.h,bottom: 10.h,right: 15.w),
                  color: Colors.white,
                  child: Column(
                      children: [
                        BrnSelectTag(
                            tags: tagList,
                            spacing: 4.w,
                            tagWidth: 60.w,
                            selectedTagBackgroundColor:Color.fromRGBO(231, 112, 27, 0.85),
                            tagTextStyle:TextStyle(color: Colors.black,fontSize:12.sp ),
                            selectedTagTextStyle:TextStyle(color: MyColors.themeColor,fontSize:12.sp ),
                            initTagState: [true],
                            onSelect: (selectedIndexes) {
                              setState(() {
                                checkType=int.parse(selectedIndexes.toString().replaceAll("[", "").replaceAll("]", ""));
                                if(checkType==0) {
                                  current = 1;
                                  allEvaluationAction(1);
                                }
                                if(checkType==1) {
                                  current = 1;
                                  goodEvaluationAction(1);

                                }
                                if(checkType==2) {
                                  current = 1;
                                  midEvaluationAction(1);

                                }
                                if(checkType==3) {
                                  current = 1;
                                  badEvaluationAction(1);
                                }
                              });
                            }),
                      ]
                  )
              ),
              EasyRefresh(
                header:
                ClassicHeader(
                  dragText: '下拉刷新',
                  armedText: '准备释放',
                  readyText: '加载中...',
                  processingText: '加载中...',
                  processedText: '刷新成功',
                  noMoreText: '暂无更多',
                  failedText: '刷新失败',
                  messageText: '刷新时间 %T',
                ),

                footer: ClassicFooter(
                  dragText: '加载更多',
                  armedText: '准备释放',
                  readyText: '加载中...',
                  processingText: '加载中...',
                  processedText: '加载成功',
                  noMoreText: '暂无更多',
                  failedText: '加载失败',
                  messageText: '加载时间 %T',
                ),
                onRefresh: _onRefresh,
                onLoad: showList.length>19?_loadMoreData:null,
                child:
                Container(
                  margin: EdgeInsets.only(top: 1.h),
                  height: screenSize.height-400.h,
                  child:ListView.builder(
                    // physics: NeverScrollableScrollPhysics(),
                      itemCount:showList.length,
                      itemBuilder: (BuildContext context, int index) {
                        return GestureDetector(
                          child: Container(
                            color: Colors.white,
                            padding: EdgeInsets.only(top: 15.h,left: 15.w,right: 15.w),
                            child:Column(
                              children: [

                                Row(
                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                  children: [
                                    Row(
                                      children: [
                                        Container(
                                          width: screenSize.width-100.w,
                                          child:Text(showList[index]['route'],maxLines: 1,style: TextStyle(color: MyColors.textColor,fontSize: 14.sp,fontWeight: FontWeight.w600, overflow:TextOverflow.ellipsis,),),

                                        )
                                      ],
                                    ),

                                    if(checkType==1)
                                      Image.asset("lib/Images/PersonCenter/我的评价好评.png",width: 57.w,height: 20.h,),
                                    if(checkType==2)
                                      Image.asset("lib/Images/PersonCenter/我的评价中评.png",width: 57.w,height: 20.h,),
                                    if(checkType==3)
                                      Image.asset("lib/Images/PersonCenter/我的评价差评.png",width: 57.w,height: 20.h,),
                                    if(checkType==0)
                                      showList[index]['level']=="POSITIVE"? Image.asset("lib/Images/PersonCenter/我的评价好评.png",width: 57.w,height: 20.h,)
                                          :showList[index]['level']=="NEUTRAL"?Image.asset("lib/Images/PersonCenter/我的评价中评.png",width: 57.w,height: 20.h,)
                                          :Image.asset("lib/Images/PersonCenter/我的评价差评.png",width: 57.w,height: 20.h,),

                                  ],
                                ),
                                SizedBox(height: 8.h,),
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    showList[index]['tags']!=null?
                                    Container(
                                      width: screenSize.width - 200.w,
                                      child: Wrap(
                                        spacing:4.w, // 两个Container之间的水平间距
                                        runSpacing: 4.h, // 行与行之间的垂直间距
                                        children: List<Widget>.from(showList[index]['tags'].map((length) {
                                          return Container(
                                            width: 75.w, // Container宽度
                                            height: 20.h, // Container高度，使其成为正方形
                                            decoration: BoxDecoration(
                                              border: Border.all(
                                                color: MyColors.hintColor, // 边框颜色
                                                width: 0.5, // 边框宽度
                                              ),
                                              color: Colors.white, // 根据状态决定颜色
                                              borderRadius: BorderRadius.circular(3.0), // 设置Container的圆角
                                            ),
                                            child: Center(
                                              child: Text(
                                                length,
                                                maxLines: 1,
                                                style: TextStyle(
                                                  overflow: TextOverflow.ellipsis,
                                                  fontSize: 10.sp,
                                                  color: MyColors.authTipColor, // 文字颜色为白色
                                                ),
                                              ),
                                            ),
                                          );
                                        })),
                                      ),
                                    ):SizedBox(),

                                    Container(
                                      width: 130.w,
                                      child: Text(showList[index]['createTime'].substring(0, 10)+"发表评论",style: TextStyle(color: MyColors.authTipColor,fontSize: 12.sp),),
                                    ),
                                  ],
                                ),


                                SizedBox(height: 10.h,),
                                Divider(height: 1.h,color: MyColors.backgreyColor,),
                              ],
                            ),

                          ) ,
                          onTap: (){

                          },
                        )
                        ;} ),
                ),
              ),
            ],
          ),
          ),
          // Container(
          //   color: Colors.white,
          //   height: 84.h,
          //   width: screenSize.width,
          //   padding: EdgeInsets.only(top: 10.h,bottom: 40.h),
          //   child: Center(
          //     child: BrnSmallMainButton(
          //       title: '拨打电话',
          //       textColor: Colors.white,
          //       bgColor: MyColors.themeColor,
          //       radius: 30,
          //       width:screenSize.width-40.w,
          //
          //       onTap: () {
          //         _makePhoneCall(shipperUserMap['phoneNum']);
          //       },
          //     ),
          //   ),
          //
          // )
        ],
      ),
    );
  }
}
